import { routeArr } from '@/router'
import { getRouters } from '@/api/login'
import Layout from '@/layout/index'
// import ParentView from '@/components/ParentView/index'

const route = {
    state: {
        // 所有的路由
        routes: [],
        // 动态新增的路由
        addRoutes: [],
        // 侧边导航栏需要的路由
        sidebarRouters: []
    },
    mutations: {
        SET_ROUTES: (state, routes) => {
            state.addRoutes = routes
            state.routes = routeArr.concat(routes)
            state.sidebarRouters = routeArr.concat(routes)
        },
    },
    actions: {
        // 生成路由
        GenerateRoutes({ commit }) {
            return new Promise(resolve => {
                // 向后端请求路由数据
                getRouters().then(res => {
                    const routerJson = JSON.parse(JSON.stringify(res.data))
                    const routers = filterRouter(routerJson)
                    routers.push({ path: '*', redirect: '/404', hidden: true })
                    commit('SET_ROUTES', routers)
                    resolve(routers)
                })
            })
        }
    }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterRouter(routerMap) {
    return routerMap.filter(route => {
        if (route.component) {
            if(!route.path || route.path==='/null' || route.path==='null'){
                route.path = "";
            }
            if (route.component === 'layout') {
                route.component = Layout
            } else if(route.component === 'parentView'){
                route.component = ParentView
            } else {
                route.component = loadView(route.component)
            }
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterRouter(route.children)
        }
        return true
    })
}

export const loadView = (view) => { // 路由懒加载
    return (resolve) => require([`@/views/${view}`], resolve)
}

export default route
